<?php

namespace App\Http\Controllers\Web;

use App\Api\Serializer\CustomSerializer;
use App\Events\PostViewCount;
use App\Http\Controllers\BaseController;
use App\Http\Requests\Web\WriteRequest;
use App\Models\Category;
use App\Models\Collect;
use App\Models\Write;
use App\Transformers\CategoryTransformer;
use App\Transformers\CollectTransformer;
use App\Transformers\WriteTransformer;
use Illuminate\Http\Request;

use phpseclib\Crypt\Random;
use Redis;
use Illuminate\Support\Facades\Cache;
class WriteController extends BaseController
{

    public function index(Request $request)
    {

        $type = $request->input('type');
        if ($type =='all'){
            $category = Category::paginate(8);
            return $this->response->paginator($category,new CategoryTransformer());
        }else {
            $title = $request->input('title');
            $category_id = $request->input('category_id');
            $is_on = $request->input('is_on');
            $subs = $request->input('subs');
            $lab = $request->input('labs');
//        $title = $request->input('title');
            $write = Write::when($title, function ($query) use ($title) {
                $query->where('title', "%$title%");
            })
                ->when($subs, function ($query) use ($subs) {
                    $query->where('subs', "%$subs%");
                })
                ->when($category_id, function ($query) use ($category_id) {
                    $query->where('category_id', $category_id);
                })
                ->when($is_on, function ($query) use ($is_on) {
                    $query->where('is_on', $is_on);
                })
                ->when($lab, function ($query) use ($lab) {
//                    foreach (Write::select(['labs']) as $labs){
//                        foreach ($labs as $b ){
//                            $query->where('labs', $b);
//                        }
//                    }
                })
                ->get();
            return $this->response->item($write, new WriteTransformer(),function ($resource, $fractal) {
                $fractal->setSerializer(new CustomSerializer());
            });

        }

    }

    public function store(WriteRequest $request)
    {
        $category = Category::find($request->category_id);
        if(!$category){
            return $this->response->errorBadRequest('分类不存在');
        }
        if ($category->is_locked == 0){
            return $this->response->errorBadRequest('分类被禁用');
        }
        $inserts = $request ->all();
        $inserts['user_id']=auth('api')->id();
        $inserts['cover']=$request->input('cover','wu.png');
        Write::create($inserts);
        return $this->response->created();
    }

//详情
    private $cacheExpires = 60;//post文章数据缓存时间
    public function show(Request $request,Write $write)
    {
            //存入缓存中,该键值key=write:cache.$write生命时间60分钟
            $write = Cache::remember('write:cache:' . $write->id, $this->cacheExpires, function () use ($write) {
                return Write::whereId($write->id)->first();
            });
            //获取客户端请求的IP
            $ip = $request->ip();
            event(new PostViewCount($write, $ip));
        return $this->response->item($write,new WriteTransformer(),function ($resource, $fractal) {
            $fractal->setSerializer(new CustomSerializer());
        });
//            return Redis::get('view');
        }



    public function update(Request $request, Write $write)
    {
        $category = Category::find($request->category_id);
        if(!$category){
            return $this->response->errorBadRequest('分类不存在');
        }
        if ($category->is_locked == 0){
            return $this->response->errorBadRequest('分类被禁用');
        }
        $write->update($request->all());
        return $this->response->noContent();

    }
//代替删除
    public function lock(Write $write){
        if($write->user_id != auth('api')->user()->id){
            return $this->response->errorBadRequest('不能删除别人的文章');
        }
        $write->is_locked = 1;
        $write->save();
        return $this->response->noContent();
    }

//    //上推荐
//    public function on(Write $write){
//        $write->is_on = $write->is_on == 0?1:0;
//        $write->save();
//        return $this->response->noContent();
//    }

    //收藏和取消
        public function collect(Request $request){
            $id = auth('api')->user()->id;
            $write_id = $request->write_id;
            $collect = new Collect();

            if ($get =Collect::where('user_id',$id)->where('write_id',$write_id)->get()->toArray()){
//            dd($get);
                Collect::where('user_id',$id)
                    ->where('write_id',$write_id)
                    ->update([
                        'is_locked'=>$get[0]['is_locked']==0?1:0
                    ]);
            }else{
                $collect->user_id = $id;
                $collect->write_id = $write_id;
                $collect->save();
            }
            return $this->response->created();
        }

        public function collect_show(Request $request){
        $user = $request->user_id == 0?auth('api')->user()->id:$request->user_id;
        $all = Collect::where('user_id',$user)->where('is_locked',0)->get();
        return $this->response->collection($all,new CollectTransformer(),function ($resource, $fractal) {
            $fractal->setSerializer(new CustomSerializer());
        });
        }
        public function my_writes(Request $request){
        $user_id = $request->user_id == 0?auth('api')->user()->id:$request->user_id;
        $all = Write::where('user_id',$user_id)->where('is_locked',0)->get();
        return $this->response->collection($all,new WriteTransformer(),function ($resource, $fractal) {
            $fractal->setSerializer(new CustomSerializer());
        });
        }

//        public function find(){
//        $in = [];
//        $key = Write::count();
//
//        if ($key<=4){
//            $all = Write::where('is_locked',0)->get();
//            return $this->response->collection($all,new WriteTransformer(),function ($resource, $fractal) {
//                $fractal->setSerializer(new CustomSerializer());
//            });
//        }
//        for ($i=0;$i<4;$i++){
//            $j = rand(0,$key);
//             $in[i] = Write::find($j);
//        }
//        return $this->response->collection($in,new WriteTransformer(),function ($resource, $fractal) {
//            $fractal->setSerializer(new CustomSerializer());
//        });
//
//
//        }

}
